////////////////////////////////////////////////////////////////////////////////
// "Toolbox" Functions
////////////////////////////////////////////////////////////////////////////////

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}


function registerOnLoad(func) {
   var orgOnLoad = window.onload;
   
   if (typeof orgOnLoad != 'function') {
      window.onload=func;
   } else {
      window.onload = function () {
         oldonload();
         func();
      }
   }
}

function formatNumber(num,prefix){
   prefix = prefix || '';
   num += '';
   var splitStr = num.split('.');
   var splitLeft = splitStr[0];
   var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
   var regx = /(\d+)(\d{3})/;
   while (regx.test(splitLeft)) {
      splitLeft = splitLeft.replace(regx, '$1' + ',' + '$2');
   }
   return prefix + splitLeft + splitRight;
}

function selectNode (node) {
   return true;
   //This is a third party function written by Martin Honnen
   //In comp.lang.javascript
   //http://groups-beta.google.com/group/comp.lang.javascript/browse_thread/thread/2b389e61c7b951f2/99b5f1bee9922c39?lnk=gst&q=(doc+%3D+node.ownerDocument)+%26%26+(win+%3D+doc.defaultView)&rnum=1&hl=en#99b5f1bee9922c39
   var selection, range, doc, win;
   if ((doc = node.ownerDocument) && (win = doc.defaultView) && typeof win.getSelection != 'undefined' && typeof doc.createRange != 'undefined' && (selection = window.getSelection()) && typeof selection.removeAllRanges != 'undefined') {
      range = doc.createRange();
      range.selectNode(node);
      selection.removeAllRanges();
      selection.addRange(range);
   } else if (document.body && typeof document.body.createTextRange != 'undefined' && (range = document.body.createTextRange())) {
      range.moveToElementText(node);
      range.select();
   }   
}

function selectNode2 (e) {
   var rightClick=false;
   if (navigator.userAgent.match('/Opera/i')) {
      return true;
   }
   var e = e || window.event;
   var node = e.target != null ? e.target : e.srcElement;
   if (!node.className.match(/code/i)) {
      node=node.parentNode;
   }   
	 if (e.button) { rightClick = (e.button == 2); }
   if (rightClick) {
      //This is a third party function written by Martin Honnen
      //In comp.lang.javascript
      //http://groups-beta.google.com/group/comp.lang.javascript/browse_thread/thread/2b389e61c7b951f2/99b5f1bee9922c39?lnk=gst&q=(doc+%3D+node.ownerDocument)+%26%26+(win+%3D+doc.defaultView)&rnum=1&hl=en#99b5f1bee9922c39
      var selection, range, doc, win;
      if ((doc = node.ownerDocument) && (win = doc.defaultView) && typeof win.getSelection != 'undefined' && typeof doc.createRange != 'undefined' && (selection = window.getSelection()) && typeof selection.removeAllRanges != 'undefined') {
         range = doc.createRange();
         range.selectNode(node);
         selection.removeAllRanges();
         selection.addRange(range);
      } else if (document.body && typeof document.body.createTextRange != 'undefined' && (range = document.body.createTextRange())) {
         range.moveToElementText(node);
         range.select();
      }
   }   
}

var popvid = false;                          // will store the window reference

function popWin(divId) {
   if (typeof(divId)=='string') { divId=document.getElementById(divId); }
   if (!popvid||popvid.closed) {
      popvid=window.open('','vidplayer','width='+(screen.width-100)+',height='+(screen.height-100)+',status=no,menu=yes');
   }
   popvid.focus();
   popvid.document.body.innerHTML='<BR><pre>'+divId.innerHTML+'</pre>';

   window.onunload=function() {
   // if the user is navigating away from the page, check to see if we
   // opened a video window and if we did, make sure it's closed.
      if (popvid) {
         popvid.close();
      }
   }
   return false;
}


function unSelectNode (e) {
   var e = e || window.event;
   var node = e.target != null ? e.target : e.srcElement;   
   //This is a third party function written by Martin Honnen
   //In comp.lang.javascript
   //http://groups-beta.google.com/group/comp.lang.javascript/browse_thread/thread/2b389e61c7b951f2/99b5f1bee9922c39?lnk=gst&q=(doc+%3D+node.ownerDocument)+%26%26+(win+%3D+doc.defaultView)&rnum=1&hl=en#99b5f1bee9922c39
   var selection, range, doc, win;
   if ((doc = node.ownerDocument) && (win = doc.defaultView) && typeof win.getSelection != 'undefined' && typeof doc.createRange != 'undefined' && (selection = window.getSelection()) && typeof selection.removeAllRanges != 'undefined') {
//      range = doc.createRange();
//      range.selectNode(node);
      selection.removeAllRanges();
//      selection.addRange(range);
   } else if (document.body && typeof document.body.createTextRange != 'undefined' && (range = document.body.createTextRange())) {
//      range.moveToElementText(node);
//      range.select();
   }   
}

///////////////////////////////////////////////////////////////////////////////
// Cookie Function
// Courtesy of quirksmode.
////////////////////////////////////////////////////////////////////////////////

function setCookie(name,value,expires, options) {
  if (options==undefined) {
     options = {};
  }
	if ( expires ) {
  	var expires_date = new Date();
    expires_date.setDate(expires_date.getDate() + expires)
	}
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + 
		( ( options.path ) ? ';path=' + options.path : '' ) +
		( ( options.domain ) ? ';domain=' + options.domain : '' ) +
		( ( options.secure ) ? ';secure' : '' );
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function killCookie(name) {
	setCookie(name,"",-1);
}

function hasCookies() {
   setCookie('checkCookie', 'test', 1);
   if (getCookie('checkCookie')) {
      killCookie('checkCookie');
      return true;
   }
   return false;
}

///////////////////////////////////////////////////////////////////////////////
// Administrative functions
////////////////////////////////////////////////////////////////////////////////

   function toggleAdmin() {
      adminID = document.getElementById('adminLayer');
      if (adminID.style.display=='none') {
         adminID.style.display='table-cell';
      } else {
         adminID.style.display='none';
      }
   }

////////////////////////////////////////////////////////////////////////////////
// Article control functions
////////////////////////////////////////////////////////////////////////////////

var _offsetSize=0;

function social(site) {
   bstr='';
   switch(site) {
      case "dzone"     : bstr="http://www.dzone.com/links/add.html?url="+_socialURL+"&title="+_socialTitle+"&description="+_socialSummary;
                         break;
      case "reddit"    : bstr="http://reddit.com/submit?url="+_socialURL+'&title='+_socialTitle+'&sr='+_socialTopic;
                         break;
      case "delicious" : bstr="http://del.icio.us/post?v=4&url="+_socialURL+'&description='+_socialTitle+'&notes='+_socialSummary+'&tags='+_socialTags;
                         break;
      case "stumble"   : bstr="http://www.stumbleupon.com/submit?url="+_socialURL+"&title="+_socialTitle;
                         break;
      case "furl"      : bstr="http://furl.net/storeIt.jsp?description="+_socialSummary+"&keywords="+_socialTags+"&t="+_socialTitle+"u="+_socialURL;
                         break;
      case "google"    : bstr="http://www.google.com/bookmarks/mark?op=add&title="+_socialTitle+"&labels="+_socialTags+"&annotation="+_socialSummary+"&bkmk="+_socialURL;
                         break;
      case "yahoo"     : bstr="http://myweb2.search.yahoo.com/myresults/bookmarklet?d="+_socialSummary+"&u="+_socialURL+"&title="+_socialTitle+"&tag="+_socialTags;
                         break;
      case "magnolia"  : bstr="http://ma.gnolia.com/bookmarklet/add?url="+_socialURL+"&title="+_socialTitle+"&tags="+_socialTags+"&description="+_socialSummary;
                         break;
      case "netkicks"  : bstr="http://www.dotnetkicks.com/submit?title="+_socialTitle+"&url="+_socialURL+"&description="+_socialSummary;
                         break;
      case "spurl"     : bstr="http://www.spurl.net/spurl.php?tags="+_socialTags+"&title="+_socialTitle+"&url="+_socialURL;
                         break;
      case "blink"     : bstr="http://www.blinklist.com/index.php?Action=Blink/addblink.php&Description="+_socialSummary+"&Url="+_socialURL+"&Title="+_socialTitle;
                         break;
      case "technorati": bstr="http://technorati.com/faves?add="+_socialURL+"&title="+_socialTitle;
                         break;
      case "simpy"     : bstr="http://www.simpy.com/simpy/LinkAdd.do?note="+_socialSummary+"&tags="+_socialTags+"&href="+_socialURL+"&title="+_socialTitle;
                         break;
      case "": bstr="";
               break;
      case "": bstr="";
               break;
   }
   if (bstr!='') {
      window.open(bstr,"", "");
   }
}

function autoSize() {
   artID = document.getElementById('art');
   fontSize = parseFloat(artID.style.fontSize);
   newSize=screen.width;
   if (newSize<600) {
      _baseSize = .8;
   }
   if ((newSize>=600)&&(newSize<=800)) {
      _baseSize = .8;
   }
   if ((newSize>=800)&&(newSize<=1000)) {
      _baseSize = 1;
   }
   if ((newSize>=1000)&&(newSize<=1100)) {
      _baseSize = 1.2;
   }
   if ((newSize>=1100)&&(newSize<=1300)) {
      _baseSize = 1.5;
   }
   if ((newSize>=1300)&&(newSize<=1500)) {
      _baseSize = 1.7;
   }
   if (newSize>=1500) {
      _baseSize = 2;
   }
   artID.style.fontSize=(_baseSize+_offsetSize)+'em';
}

function downFont() {
   _offsetSize=_offsetSize-.1;
   if (_offsetSize < -1) { _offsetSize = -1 }
   autoSize();
}

function upFont() {
   _offsetSize=_offsetSize+.1;
   if (_offsetSize > 1) { _offsetSize = 1 }
   autoSize();
}

function toggleBG() {
   artID = document.getElementById('art');
   if (artID.className=='articleBlack') {
      artID.className='article';
   } else {
      artID.className='articleBlack';
   }            
}

////////////////////////////////////////////////////////////////////////////////
// Clock Functions
////////////////////////////////////////////////////////////////////////////////

   months=new Array("January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
   calDays=new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
   
   function pad(i) {
      //simple function to just add a zero in front of numbers less than zero (so we get 12:05 instead of 12:5)
      if (i < 10) {
         i = "0"+i;
      }
      return(i);
   }
   
   function doClock() {
      setTimeout( "doClock()", 1000 );
      t = new Date();
      m = t.getMonth();
      d = t.getDay();
      dt = t.getDate();
      y = t.getFullYear();
      h = t.getHours();
      if (h < 12) {
         ap="AM";
      } else {
         ap="PM";
         h=h-12;
      }
      mn= pad(t.getMinutes());
      s = pad(t.getSeconds());
      if (h==0) {
         h = 12
      }
      clockID.innerHTML=calDays[d]+", "+months[m]+" "+dt+" "+y+"<BR>"+h+":"+mn+":"+s+" "+ap;
   }

////////////////////////////////////////////////////////////////////////////////
// Ajax Constructor
////////////////////////////////////////////////////////////////////////////////

   function ajaxObject(layer, url) {                                    // This is the object constructor
      var that=this;                                                    // A workaround for some javascript idiosyncrocies
      var updating = false;                                             // Set to true if this object is already working on a request
      this.callback = function() {}                                     // A post-processing call -- a stub you overwrite.
   
      this.isUpdating = function() {
          return(updating);
      }
   
      this.update = function(passData) {                                // Initiates the server call.
         if (updating==true) { return false; }                          // Abort if we're already processing a call.
         updating=true;                                                 // Set the updating flag.
         var AJAX = null;                                               // Initialize the AJAX variable.
         if (window.XMLHttpRequest) {                                   // Are we working with mozilla?
            AJAX=new XMLHttpRequest();                                  //  Yes -- this is mozilla.
         } else {                                                       // Not Mozilla, must be IE
            AJAX=new ActiveXObject("Microsoft.XMLHTTP");                //  Wheee, ActiveX, how do we format c: again?
         }                                                              // End setup Ajax.
         if (AJAX==null) {                                              // If we couldn't initialize Ajax...
            alert("Your browser doesn't support AJAX.");                // Sorry msg.						
            return false                                                // Return false (WARNING - SAME AS ALREADY PROCESSING!)
         } else {
            AJAX.onreadystatechange = function() {                      // When the browser has the request info..
               if (AJAX.readyState==4 || AJAX.readyState=="complete") { //   see if the complete flag is set.
                  var tmp = AJAX.responseText;
                  if (LayerID!=null) {
                     LayerID.innerHTML=tmp;                                //   It is, so put the new data in the object's layer
                  }
                  delete AJAX;                                          //   delete the AJAX object since it's done.
                  updating=false;                                       //   Set the updating flag to false so we can do a new request
                  that.callback(tmp);                                   //   Call the post-processing function.
               }                                                        // End Ajax readystate check.
            }                                                           // End create post-process fucntion block.
            var timestamp = new Date();                                 // Get a new date (this will make the url unique)
            var uri=urlCall+'?'+passData+'&timestamp='+(timestamp*1);   // Append date to url (so the browser doesn't cache the call)                       
            AJAX.open("GET", uri, true);                                // Open the url this object was set-up with.
            AJAX.send(null);                                            // Send the request.
            return true;                                                // Everything went a-ok.
         }                                                              // End Ajax setup aok if/else block                 
      }
         
      // This area set up on constructor calls.
      var LayerID = document.getElementById(layer);                     // Remember the layer associated with this objec.t                             
      var urlCall = url;                                                // Remember the url associated with this object.
   }
     
////////////////////////////////////////////////////////////////////////////////
// Handle Contact (a small spambot foil)
////////////////////////////////////////////////////////////////////////////////

   var storedSubject = '';

   function contactCallback(data) {
      tmp='ma';
      tmp+='il';
      tmp+='to';
      tmp+=':';
      tmp+=data;
      tmp+='?';
      tmp+='subj';
      tmp+='ect="re:'+escape(storedSubject)+'"';
      document.location.href=tmp;
   }
   
   function handleContact(subject) {
      contact.update('id=74619');
      storedSubject =subject;
      return false;
   }
   
////////////////////////////////////////////////////////////////////////////////
// Shortcuts
////////////////////////////////////////////////////////////////////////////////

function $(el) {
   return document.getElementById(el);
}


function getCSSRule(ruleName, deleteFlag) {               // Return requested style obejct
   ruleName=ruleName.toLowerCase();                       // Convert test string to lower case.
   if (document.styleSheets) {                            // If browser can play with stylesheets
      for (var i=0; i<document.styleSheets.length; i++) { // For each stylesheet
         var styleSheet=document.styleSheets[i];          // Get the current Stylesheet
         var ii=0;                                        // Initialize subCounter.
         var cssRule=false;                               // Initialize cssRule. 
         do {                                             // For each rule in stylesheet
            if (styleSheet.cssRules) {                    // Browser uses cssRules?
               cssRule = styleSheet.cssRules[ii];         // Yes --Mozilla Style
            } else {                                      // Browser usses rules?
               cssRule = styleSheet.rules[ii];            // Yes IE style. 
            }                                             // End IE check.
            if (cssRule)  {                               // If we found a rule...
               if (cssRule.selectorText.toLowerCase()==ruleName) { //  match ruleName?
                  if (deleteFlag=='delete') {             // Yes.  Are we deleteing?
                     if (styleSheet.cssRules) {           // Yes, deleting...
                        styleSheet.deleteRule(ii);        // Delete rule, Moz Style
                     } else {                             // Still deleting.
                        styleSheet.removeRule(ii);        // Delete rule IE style.
                     }                                    // End IE check.
                     return true;                         // return true, class deleted.
                  } else {                                // found and not deleting.
                     return cssRule;                      // return the style object.
                  }                                       // End delete Check
               }                                          // End found rule name
            }                                             // end found cssRule
            ii++;                                         // Increment sub-counter
         } while (cssRule)                                // end While loop
      }                                                   // end For loop
   }                                                      // end styleSheet ability check
   return false;                                          // we found NOTHING!
}                                                         // end getCSSRule 

function noads() {
   var el = getCSSRule('.adBar');
       el.style.display='none';
   setCookie('noads', 'noads', 1);
   if (navigator.userAgent.indexOf('MSIE')) {
      document.location.href=document.location.href;
   }
   
}

